package com.lambkit.core.loadbalance;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * IPHash
 * 根据每个每个请求ip（也可以是某个标识）ip.hash() % server.size()
 * @author yangyong
 *
 */
public class IpHash {
	
	public Server selectServer(List<Server> serverList, String ip) {
        int ipHash = ip.hashCode();
        return serverList.get(ipHash % serverList.size());
    }

    public static void main(String[] args) {
        List<Server> serverList = new ArrayList<>();
        serverList.add(new Server(1, "服务器1"));
        serverList.add(new Server(2, "服务器2"));
        serverList.add(new Server(3, "服务器3"));
        IpHash lb = new IpHash();
        List<String> ips = Arrays.asList("192.168.9.5", "192.168.9.2", "192.168.9.3");
        for (int i = 0; i < 10; i++) {
            for (String ip : ips) {
                Server selectedServer = lb.selectServer(serverList, ip);
                System.out.format("请求ip:%s，选择服务器%s\n", ip, selectedServer.toString());
            }
        }
    }
}
